package com.ybf.api.controller;

import com.ybf.api.common.ResultResponse;
import com.ybf.api.entity.PageRequest;
import com.ybf.api.entity.FileDetails;
import com.ybf.api.entity.User;
import com.ybf.api.service.FileDetailsService;
import com.ybf.api.utils.EncryptUtils;
import com.ybf.api.utils.FileUtils;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;

import static com.ybf.api.utils.Utils.mapToObject;

/**
 * @author ybf
 * @since 2024-09-26
 */
@Controller
@RequestMapping("/file")
public class FileDetailsController {

    @Resource
    FileDetailsService fileDetailsService;

    @Value("${file.upload-dir}")
    private String uploadDir;
    // 上传文件
    @PostMapping("/upload")
    @ResponseBody
    public ResultResponse upload(@RequestParam("file") MultipartFile file) throws IOException {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new RuntimeException("上传的文件为空");
        }

        String sha256Hex = "";

//        FileUtils.extractMetadata(file.getInputStream());

        try {
            sha256Hex = EncryptUtils.calculateSHA256(file.getInputStream());
            System.out.println("文件的SHA-256哈希值为: " + sha256Hex);
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        FileDetails fileInfo = fileDetailsService.info(sha256Hex);

        if (fileInfo != null) {
            return ResultResponse.ok(fileInfo);
        }

        // 获取图片的拍摄时间、设备、分辨率等信息

        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.lastIndexOf(".") > 0) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 生成唯一的文件名
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

        // 获取当前日期并格式化为年份和日期
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MMdd");
        String datePath = currentDate.format(formatter);

        // 创建年份和日期目录
        Path dateDirectory = Paths.get(uploadDir, datePath);
        if (!Files.exists(dateDirectory)) {
            Files.createDirectories(dateDirectory);
        }

        // 将文件保存到指定目录
//        Path destinationFile = Paths.get(uploadDir).resolve(uniqueFileName);
        Path destinationFile = dateDirectory.resolve(uniqueFileName);
        try {
            Files.copy(file.getInputStream(), destinationFile, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 获取针对uploadDir的相对路径
        String relativePath = dateDirectory.toAbsolutePath().toString().substring(uploadDir.length());

        // 获取文件大小
        long fileSize = file.getSize();

        // 更新数据库
        FileDetails fileDetails = new FileDetails();
        fileDetails.setFilename(originalFilename);
        fileDetails.setFilepath(relativePath);
        fileDetails.setFilesize(Long.valueOf(fileSize).intValue());
        fileDetails.setFiletype(fileExtension);
        fileDetails.setHash(sha256Hex);

      

        System.out.println("fileDetails:------" + fileDetails.toString());
        fileDetailsService.add(fileDetails);

        return ResultResponse.ok(fileDetails);
    }

    @Operation(summary = "获取列表")
    @GetMapping("/list")
    @ResponseBody
    public ResultResponse list(
            @RequestBody Map reqBody
    ) {
        FileDetails filedetails = (FileDetails) mapToObject(FileDetails.class, reqBody);
        PageRequest pageRequest = (PageRequest) mapToObject(PageRequest.class, reqBody);
        return ResultResponse.ok(fileDetailsService.list(filedetails, pageRequest));
    }

    @Operation(summary = "获取详情")
    @GetMapping("/info")
    @ResponseBody
    public ResultResponse info(
            @RequestBody(required = true) Map req
    ) {
        FileDetails filedetails = fileDetailsService.info((Integer) req.get("id"));
        return filedetails != null ? ResultResponse.ok(filedetails) : ResultResponse.error("error");
    }

    @Operation(summary = "删除")
    @GetMapping("/delete")
    @ResponseBody
    public ResultResponse delete(@RequestBody Map req) {
        Boolean status = fileDetailsService.delete((Integer) req.get("id"));
        return status ? ResultResponse.ok(true) : ResultResponse.error(false);
    }

    @Operation(summary = "编辑详情", description = "不传id就是新增，传了就是编辑")
    @PostMapping("/edit")
    @ResponseBody
    public ResultResponse edit(@Valid @RequestBody(required = true) FileDetails filedetails) {
        Integer status = fileDetailsService.edit(filedetails);
        return status > 0 ? ResultResponse.ok(status) : ResultResponse.error(false);
    }
}
